package com.swak.storage;

import java.io.File;
import java.util.UUID;

import com.swak.codec.Digests;
import com.swak.config.setting.Settings;
import com.swak.utils.FileUtils;

public class AbstractStorage {

	final File tempPath;

	AbstractStorage() {
		Settings settings = Settings.intSettings();
		this.tempPath = settings.getTempFile();
	}

	public void put(String name, byte[] datas) {
		File file = this.getStorageFile(name);
		FileUtils.write(file, datas);
	}

	public byte[] get(String name) {
		if (name == null) {
			return null;
		}
		File file = this.getStorageFile(name);
		if (file != null && file.exists()) {
			return FileUtils.read(file);
		}
		return null;
	}

	public void delete(String name) {
		File file = this.getStorageFile(name);
		if (file.exists() && file.isFile()) {
			file.delete();
		}
	}

	public File file(String name) {
		return getStorageFile(name);
	}

	protected File getStoragePath() {
		return tempPath;
	}

	protected File getStorageFile(String name) {
		return new File(getStoragePath(), encodeName(name));
	}

	protected String encodeName(String name) {
		return Digests.md5(name);
	}

	public File file(String name, String suffix) {
		return getStorageFile(name);
	}

	protected File getStorageFile(String name, String suffix) {
		return new File(getStoragePath(), encodeName(name) + "." + suffix);
	}

	public File randomfile(String suffix) {
		return getStorageFile(UUID.randomUUID().toString(), suffix);
	}
}
